package com.etooling.framework.controller;

import com.etooling.framework.entity.FuncModule;
import com.etooling.framework.repository.FuncModuleRepository;
import com.etooling.framework.svo.ReplyObj;
import com.etooling.framework.utils.VoToPoUtil;
import com.etooling.framework.utils.WebUtils;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Controller
@EnableAutoConfiguration
@RequestMapping(value = "/admin/funcModule")
/**
 * @title: OrgController
 * @description: 功能模块管理
 * @author 周志荣
 * @date 2020/12/18 17:57
 */
public class FuncModuleController {
    @Autowired
    FuncModuleRepository funcModuleRepository;


    @RequestMapping("/add")
    @ResponseBody
    /**
     　　* @description:  新增机构
     　　* @param [request, funcModule, pid]
     　　* @return com.irobot.framework.svo.ReplyObj
     　　* @throws
     　　* @author 周志荣
     　　* @date 2020/12/18 18:13
     　　*/
    ReplyObj add(HttpServletRequest request,
                 FuncModule funcModule
    ) {
        // funcModule.setStatus("启用");
        if (!WebUtils.checkStr(funcModule.getParentId())) {
            funcModule.setParentId("root");
        }
        funcModuleRepository.save(funcModule);
        return WebUtils.flushObjSuccess(funcModule);
    }

    @RequestMapping("updateSeq")
    @ResponseBody
    ReplyObj updateSeq(HttpServletRequest request,
                       @RequestParam(defaultValue = "", required = false, value = "parentId") String parentId,
                       @RequestParam(defaultValue = "0", required = false, value = "oldSeq") Integer oldSeq,
                       @RequestParam(defaultValue = "0", required = false, value = "newSeq") Integer newSeq) {
        try {
            if (!WebUtils.checkStr(parentId) || !WebUtils.checkStr(oldSeq) || !WebUtils.checkStr((newSeq))) {
                return WebUtils.flushFailure("数据异常，无法修改排序");
            }
            // 收集最大排序号
            Integer maxSeq = funcModuleRepository.getMaxSeq(parentId);

            if (newSeq > maxSeq || newSeq < 1) {
                return WebUtils.flushFailure("序号超出已有范围");
            }

            funcModuleRepository.updateSeq(oldSeq, newSeq, parentId);
        } catch (Exception e) {
            e.printStackTrace();
            return WebUtils.flushFailure();
        }
        return WebUtils.flushSuccess("修改成功");
    }

    @RequestMapping("/update")
    @ResponseBody
        /*
         * @description: 修改机构
         * @param [request, org, newOrgId]
         * @return com.irobot.framework.svo.ReplyObj
         * @throws
         * @author 周志荣
         * @date 2020/12/18 18:13
         */
    ReplyObj update(HttpServletRequest request,
                    FuncModule funcModule
    ) {
        try {
            FuncModule po = funcModuleRepository.findById(funcModule.getId()).get();
            VoToPoUtil.copyProperties(po, funcModule, new String[]{"parentId"});
            funcModuleRepository.save(po);
            return WebUtils.flushObjSuccess(po);
        } catch (Exception e) {
            e.printStackTrace();
            return WebUtils.flushFailure();
        }

    }

    @RequestMapping("/del")
    @ResponseBody
    ReplyObj del(HttpServletRequest request,
                 @RequestParam(defaultValue = "", required = false, value = "id") String id
    ) {
        try {
            FuncModule funcModule = funcModuleRepository.getOne(id);
            //funcModule.setStatus("停用");
            //删除用户相关
            funcModuleRepository.deleteFuncnByRoleModul(funcModule.getId());
            funcModuleRepository.delete(funcModule);
            return WebUtils.flushSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return WebUtils.flushFailure();
        }

    }

    @RequestMapping("/getFuncModuleTree")
    @ResponseBody
    ReplyObj getFuncModuleTree(HttpServletRequest request,
                               @RequestParam(defaultValue = "", required = false, value = "parentFuncId") String parentFuncId
    ) {
        try {
            List<FuncModule> resultList = new ArrayList<>();
            List<FuncModule> funcModuleList = funcModuleRepository.getAllFuncModuleList();
            //整理成完成的树结构
            if (CollectionUtils.isNotEmpty(funcModuleList)) {
                Map<String, List<FuncModule>> groupByMap = funcModuleList.stream()
                        .collect(Collectors.groupingBy(lt -> lt.getParentId()));
                resultList = this.getTree(groupByMap, "root");
            }
            return WebUtils.flushSuccess(resultList);
        } catch (Exception e) {
            e.printStackTrace();
            return WebUtils.flushFailure();
        }
    }


    public List<FuncModule> getTree(Map<String, List<FuncModule>> allNodeMap, String parentId) {
        List<FuncModule> list = allNodeMap.get(parentId);
        List<FuncModule> allTree = new ArrayList<>();
        list = allNodeMap.get(parentId);
        if (list != null && list.size() > 0) {
            for (FuncModule item : list) {
                List<FuncModule> children = null;
                if (allNodeMap.containsKey(item.getId())) {
                    children = getTree(allNodeMap, item.getId());
                }
                if (CollectionUtils.isNotEmpty(children)) {
                    item.setChildren(children);
                }
                allTree.add(item);
            }
        }
        return allTree;
    }


}
